/**
 * Created by YJH on 2018/5/24.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    TouchableOpacity,
    Image,
    DeviceEventEmitter,
    WebView,
} from 'react-native';

import NavigationBarComponent from './NavigationBarComponent'


const URL = 'https://reactnative.cn/docs/0.39/webview.html';
export default class WebViewTest extends Component<Props> {

    constructor(props) {
        super(props);
        this.state = ({
            url: URL,
            inputTxt:'',
            title:'',
            isBack:false,
        });
    }

    goBack(){
        if(this.state.isBack){
            this.webView.goBack();
        }else{
            DeviceEventEmitter.emit('showToast','已经到顶部了');
        }
    }

    goTo(){
        this.setState({
            url: this.state.inputTxt,
        })
    }

    onNavigationStateChange(result){
        this.setState({
            title:result.title,
            isBack:result.canGoBack,
        })
    }

    render() {
        return <View style={styles.container}>
            <NavigationBarComponent
                style={{backgroundColor: '#2196F3'}}
                title={'WebView'}
                statusBar={{backgroundColor: '#2196F3'}}/>

            <View style={styles.view_top}>
                <Text style={styles.text} onPress={() => {
                    this.goBack();
                }}>返回</Text>
                <TextInput
                    style={{height:50,flex:1}}
                    onChangeText={result => {
                        this.setState({
                            inputTxt:result,
                        })
                }}
                defaultValue={this.state.url}/>
                <Text style={styles.text} onPress={() => {
                    this.goTo();
                }}>进入</Text>

            </View>

            <WebView
                //通过这种方法，相当于拿到了组件的对象
                ref={webView=>this.webView=webView}
                style={styles.container}
                source={{uri: this.state.url}}
                onNavigationStateChange={result=>{
                    this.onNavigationStateChange(result)
                }}
            />
        </View>

    }
}

const styles = StyleSheet.create(
    {
        container: {
            flex: 1,
        },

        view_top: {
            margin: 5,
            flexDirection: 'row',
            alignItems: 'center',

        },
        text: {
            marginHorizontal: 10,
            fontSize: 16,
            color: 'black',
            alignSelf: 'center',
        }
    }
)